/*
 * All rights Reserved, Designed By DataDriver
 * Copyright:    DataDriver.Inc
 * Company:      Zhuo Wo Infomation Technology (ShangHai) CO.LTD
 */
package com.sun.unsafe;


import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * CallAble接口
 */
public class CallableTest {


    /**
     * Callable接口和RunnAble接口的区别？
     * 1、Callable有返回值
     * 2、Callable可以抛出异常
     * 3、实现的方法不同run() call()
     *
     * @param args
     */
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        MyThread myThread = new MyThread();

        //那怎么启动callable的线程呢？？

        //线程启动是通过thread.start();

        //思路：可以先通过Runnable接口，来最终找到Thread

        //--->Runnable-->RunnableFuture -->FutureTask

        FutureTask futureTask = new FutureTask(myThread);  //适配类

        //开了两个线程会打印几个call呢？？？？
        new Thread(futureTask, "A").start();
        new Thread(futureTask, "B").start();  //结果会被缓存，效率高

        Integer o = (Integer) futureTask.get();  //这个方法可能会产生阻塞，所以放到最后执行;得到Callable的结果

        //或者使用异步通信来执行
        System.out.println("结果" + o);

        /**
         * 细节
         * 1、有缓存
         * 2、结果可能需要等待，会阻塞！
         */
    }

}


class MyThread implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        System.out.println("callable....call()....");
        return 1024;
    }
}
